package com.cloud.encrypting_cloud_storage.controller;

import com.cloud.encrypting_cloud_storage.entity.User;
import com.cloud.encrypting_cloud_storage.enums.StatusEnum;
import com.cloud.encrypting_cloud_storage.exceptions.JsonException;
import com.cloud.encrypting_cloud_storage.models.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author leon
 * @Description: TODO
 * @date 2022年04月08日 20:25
 */
@Controller
@Slf4j
public class LoginController extends BaseController {


    @GetMapping("/login")
    public ModelAndView login() {
        return new ModelAndView("user/login");
    }

    @PostMapping("/login")
    public ModelAndView login(@RequestBody User user, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        // 用户验证
        User sessionUser = authenticationService.authentication(user);
        request.getSession().setAttribute(userKey,sessionUser);
        mav.addObject(userKey,sessionUser);
        mav.setViewName("main/main");
        return mav;
    }


    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public ApiResponse register(@RequestBody User user) {

        // 发送Email、客户端随机数、加密的主密钥和哈希值到服务器
        if (userService.findUserByEmail(user.getEmail()) != null) {
            return ApiResponse.ofStatus(StatusEnum.REGISTERED_USER);
        }
        initUser(user);
        userService.insert(user);
        return ApiResponse.ofSuccess();
    }

    @GetMapping("/register")
    public ModelAndView register(){
        return new ModelAndView("/user/register");
    }

    /**
     * 初始化用户，生成用户根结点
     *
     * @param user
     */
    private void initUser(User user) {
        user.setRTime(LocalDateTime.now());
        UUID uuid = UUID.randomUUID();
        user.setInode(uuid.toString());
    }

    /**
     * 检查用户是否存在
     *
     * @return ApiResponse
     */
    @GetMapping("/check")
    @ResponseBody
    public ApiResponse check(String username,@RequestParam String register) {
        User userByName = userService.findUserByName(username);
        if(userByName==null){
            throw new JsonException(StatusEnum.NOT_USER);
        }
        return ApiResponse.ofSuccess(userByName.getClientRandomValue());
    }


    @GetMapping("/logout")
    public void logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
    }


}
